#include "connector.h"
#include <QDebug>
#include <Qvariant>

#include <QNetworkProxyFactory>

Connector::Connector(QObject *parent) :
	QObject(parent),
	m_pReply(NULL),
	m_redirectCount(0)
{
	QNetworkProxyFactory::setUseSystemConfiguration(true);
	m_pManager = new QNetworkAccessManager(this);
}

Connector::~Connector(){
	m_pReply->deleteLater();
	delete m_pManager;
}

void Connector::connectToUrl(const QString &url){
	if( m_pReply )
		m_pReply->deleteLater();

	//qDebug()<<url;
	m_pReply = m_pManager->get( QNetworkRequest( QUrl(url) ) );



	connect(m_pReply, SIGNAL(finished()), this, SLOT(slotFinish()));


	connect(m_pReply, SIGNAL(error(QNetworkReply::NetworkError)),
			this, SLOT(slotError(QNetworkReply::NetworkError)));
	connect(m_pReply, SIGNAL(sslErrors(QList<QSslError>)),
			this, SLOT(slotSslErrors(QList<QSslError>)));
}

void Connector::slotFinish(){
	QVariant variant =
			m_pReply->attribute(QNetworkRequest::RedirectionTargetAttribute);

	if( variant.isValid() ){
		if( m_redirectCount < 5 ){
			m_redirectCount++;
			connectToUrl( variant.toUrl().toString() );
		}else{
			m_redirectCount = 0;
			qWarning() << "Connector=> too many redirections";
			return;
		}
	}else{
		receivedData = m_pReply->readAll();

		emit dataReaded( receivedData );
	}
}


void Connector::slotError(QNetworkReply::NetworkError error){
	qDebug() << "Connector=>error:" << error << m_pReply->errorString();
}

void Connector::slotSslErrors(QList<QSslError> errors){
	qDebug() << "Connector=>SslErrors:" << errors;
}
